package com.yunyouyi.cpicture.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunyouyi.cpicture.domain.picture.service.PictureDomainService;
import com.yunyouyi.cpicture.infrastructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yunyouyi.cpicture.infrastructure.exception.BusinessException;
import com.yunyouyi.cpicture.infrastructure.exception.ErrorCode;
import com.yunyouyi.cpicture.interfaces.dto.picture.*;
import com.yunyouyi.cpicture.domain.picture.entity.Picture;
import com.yunyouyi.cpicture.domain.user.entity.User;
import com.yunyouyi.cpicture.interfaces.vo.picture.PictureVO;
import com.yunyouyi.cpicture.application.service.PictureApplicationService;
import com.yunyouyi.cpicture.infrastructure.mapper.PictureMapper;
import com.yunyouyi.cpicture.application.service.UserApplicationService;
import com.yunyouyi.cpicture.interfaces.vo.user.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author yunyouyi
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-04-04 10:55:47
*/
@Service
@Slf4j
public class PictureApplicationServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureApplicationService {

    @Resource
    private PictureDomainService pictureDomainService;

    @Resource
    private UserApplicationService userApplicationService;

    /**
     * 上传图片
     * @param inputSource
     * @param pictureUploadDTO
     * @param loginUser
     * @return 图片封装类
     */
    public PictureVO uploadPicture(Object inputSource, PictureUploadDTO pictureUploadDTO, User loginUser) {
        return pictureDomainService.uploadPicture(inputSource, pictureUploadDTO, loginUser);
    }

    /**
     * 获取单个图片封装
     * @param picture
     * @param request
     * @return 图片封装类
     */
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.obj2Vo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userApplicationService.getUserById(userId);
            UserVO userVO = userApplicationService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }
    /**
     * 获取图片分页封装
     * @param picturePage
     * @param request
     * @return 分页对象
     */
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        log.info("pictureList{}",pictureList);
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        log.info("picturePage.getTotal(){}",picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::obj2Vo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userApplicationService.listByIds(userIdSet).stream()//？
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userApplicationService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 获取查询包装类
     * @param pictureQueryDTO
     * @return QueryWrapper
     */
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryDTO pictureQueryDTO) {
        return pictureDomainService.getQueryWrapper(pictureQueryDTO);
    }
    /**
     * 图片审核
     * @param pictureReviewDTO
     * @param loginUser
     * @return
     */
    public boolean doPictureReview(PictureReviewDTO pictureReviewDTO, User loginUser) {
        return pictureDomainService.doPictureReview(pictureReviewDTO, loginUser);
    }
    /**
     * 填充审核参数
     * @param picture
     * @param loginUser
     */
    public void fileReviewParam(Picture picture, User loginUser){
        pictureDomainService.fileReviewParam(picture, loginUser);
    }
    /**
     * 批量上传图片
     * @param pictureUploadByBatchDTO
     * @param loginUser
     * @return 成功上传数量
     */
    public Integer uploadPictureByBatch(PictureUploadByBatchDTO pictureUploadByBatchDTO, User loginUser) {
        return pictureDomainService.uploadPictureByBatch(pictureUploadByBatchDTO, loginUser);
    }

    /**
     *  清理图片
     * @param oldPicture
     */
    @Async
    public void clearPictureFile(Picture oldPicture) {
        pictureDomainService.clearPictureFile(oldPicture);
    }


    /**
     * 删除图片
     * @param pictureId
     * @param loginUser
     */
    public boolean deletePicture(Long pictureId, User loginUser) {
        return pictureDomainService.deletePicture(pictureId, loginUser);
    }

    /**
     * 检查图片的操作权限
     * @param picture
     * @param loginUser
     */
    @Override
    public void checkPictureAuth(Picture picture, User loginUser) {
        pictureDomainService.checkPictureAuth(picture, loginUser);
    }

    /**
     * tags和分类批量更新
     * @param pictureEditByBatchDTO
     * @param loginUser
     */
    @Override
    @Transactional
    public void editPictureByBatch(PictureEditByBatchDTO pictureEditByBatchDTO, User loginUser){
        pictureDomainService.editPictureByBatch(pictureEditByBatchDTO, loginUser);
    }

    /**
     * 创建扩图任务
     *
     * @param createPictureOutPaintingTaskDTO
     * @param loginUser
     * @return
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPainting(CreatePictureOutPaintingTaskDTO createPictureOutPaintingTaskDTO, User loginUser){
        return pictureDomainService.createPictureOutPainting(createPictureOutPaintingTaskDTO, loginUser);
    }

    @Override
    public void validPicture(Picture picture) {
        if(picture == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        picture.validPicture();
    }
}









